from datetime import datetime
from sqlalchemy import event

from base.base_entity import BaseEntity
from util.toolkit import IdWorker


@event.listens_for(BaseEntity, 'before_insert', propagate=True)
def before_insert(mapper, connection, target):
    print(f"[Audit] before_insert triggered for {target.__class__.__name__}")
    user_id = IdWorker.GetIdStr()
    now = datetime.now()
    target.id = user_id
    target.gmt_created = now
    target.created_by = 0


# 定义事件监听器
@event.listens_for(BaseEntity, 'before_update', propagate=True)
def receive_before_insert(mapper, connection, target):
    now = datetime.now()
    target.gmt_modified = now
    target.modified_by = 0
